/*
The MIT License
Copyright (c) 2019 Lehrstuhl Informatik 11 - RWTH Aachen University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE

This file is part of embeddedRTPS.

Author: i11 - Embedded Software, RWTH Aachen University
*/

#include "lwip/sys.h"
#include "rtps/storages/CacheChange.h"
#include "rtps/entities/StatefulWriter.h"
#include "rtps/messages/MessageFactory.h"
#include "rtps/utils/Log.h"
#include <string.h>
#include <stdio.h>


#if SFW_VERBOSE && RTPS_GLOBAL_VERBOSE
#include "rtps/utils/printutils.h"
#define SFW_LOG(...)                                                           \
  if (true) {                                                                  \
    printf("[Stateful Writer %s] ", sfw->writer.m_attributes.topicName);             \
    printf(__VA_ARGS__);                                                       \
    printf("\n");                                                              \
  }
#else
#define SFW_LOG(...) //
#endif

void rtps_StatefulWriterT_destruct(struct rtps_StatefulWriter *sfw) {
  sfw->m_running = false;
  while (sfw->m_thread_running) {
    sys_msleep(500); // Required for tests/ Join currently not available /
    //  increased because Segfault in Tests if(sys_mutex_valid(&m_mutex)){
    //    sys_mutex_free(&sfw->m_mutex);
    //  }
  }
}


bool rtps_StatefulWriterT_init(struct rtps_StatefulWriter *sfw, TopicData attributes,
                                          TopicKind_t topicKind,
                                          ThreadPool *threadPool,
                                          NetworkDriver *driver,
                                          bool enfUnicast) {
  if (sys_mutex_new(&sfw->m_mutex) != ERR_OK) {

    SFW_LOG("Failed to create mutex.\n");

    return false;
  }
  rtps_Writer_Construct(&sfw->writer);
  sfw->writer.m_bstateful = true;
  sfw->m_transport = driver;
  sfw->writer.m_attributes = attributes;
  sfw->m_topicKind = topicKind;
  sfw->m_packetInfo.srcPort = attributes.unicastLocator.port;
  sfw->m_enforceUnicast = enfUnicast;
  sfw->mp_threadPool = threadPool;
  if (rtps_EntityId_t_operator_equal(&sfw->writer.m_attributes.endpointGuid.entityId,
			  &ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER)) {
    sfw->m_heartbeatThread = sys_thread_new("HBThreadPub", rtps_StatefulWriterT_hbFunctionJumppad, sfw,
                                       HEARTBEAT_STACKSIZE,
                                       THREAD_POOL_WRITER_PRIO);
  } else if (rtps_EntityId_t_operator_equal(&sfw->writer.m_attributes.endpointGuid.entityId,
             &ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_WRITER)) {
    sfw->m_heartbeatThread = sys_thread_new("HBThreadSub", rtps_StatefulWriterT_hbFunctionJumppad, sfw,
                                       HEARTBEAT_STACKSIZE,
                                       THREAD_POOL_WRITER_PRIO);
  } else {
    sfw->m_heartbeatThread = sys_thread_new("HBThread", rtps_StatefulWriterT_hbFunctionJumppad, sfw,
                                       HEARTBEAT_STACKSIZE,
                                       THREAD_POOL_WRITER_PRIO);
  }

  sfw->writer.m_is_initialized = true;
  sfw->m_nextSequenceNumberToSend.high = 0;
  sfw->m_nextSequenceNumberToSend.low = 1;
  sfw->m_hbCount.value = 1;
  sfw->m_running = true;
  sfw->m_thread_running = false;
  SequenceNumber_t lastUsed = {0,0};
  sfw->m_history = rtps_SimpleHistoryCache_init(lastUsed);
  return true;
}

bool rtps_StatefulWriterT_addNewMatchedReader(struct rtps_StatefulWriter *sfw,
    const ReaderProxy *newProxy) {
#if SFW_VERBOSE && RTPS_GLOBAL_VERBOSE
  SFW_LOG("New reader added with id: ");
  printGuid(newProxy->remoteReaderGuid);
#endif

  bool success = rtps_MemoryPool_add(sfw->writer.m_proxies, (void *)newProxy);
  if (!sfw->m_enforceUnicast){
    rtps_StatefulWriter_manageSendOptions(sfw);
  }
  return success;
}

void rtps_StatefulWriterT_manageSendOptions(struct rtps_StatefulWriter *sfw) {

  SFW_LOG("Search for Multicast Partners!\n");
    uint8_t *ptmp;
    uint8_t *pblk;
    uint8_t *pdata;
    uint32_t offset;
    uint8_t *ptmp2;
    uint8_t *pblk2;
    uint8_t *pdata2;
    uint32_t offset2;
    ReaderProxy *proxy;//???
    ReaderProxy *avproxy;//???

    RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    if (proxy->remoteMulticastLocator.kind == LOCATOR_KIND_INVALID) {
      proxy->suppressUnicast = false;
      proxy->useMulticast = false;
    } else {
      bool found = false;
      RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset2, ptmp2, pblk2, pdata2) {
        avproxy = (ReaderProxy *)pdata2;
        if (avproxy->remoteMulticastLocator.kind == LOCATOR_KIND_UDPv4 &&
            rtps_Locator_getIp4Address(&avproxy->remoteMulticastLocator).addr ==
                rtps_Locator_getIp4Address(&proxy->remoteMulticastLocator).addr &&
            rtps_Locator_getIp4Address(&avproxy->remoteLocator).addr !=
                rtps_Locator_getIp4Address(&proxy->remoteLocator).addr) {
          if (avproxy->suppressUnicast == false) {
            avproxy->useMulticast = false;
            avproxy->suppressUnicast = true;
            proxy->useMulticast = true;
            proxy->suppressUnicast = true;
            SFW_LOG("Found Multicast Partner!\n");

            if (rtps_EntityId_t_operator_equal(&avproxy->remoteReaderGuid.entityId,
                &proxy->remoteReaderGuid.entityId)) {
              proxy->unknown_eid = true;

              SFW_LOG("Found different EntityIds, using UNKNOWN_ENTITYID\n");
            }
          }
          found = true;
        }
      }
      if (!found) {
        proxy->useMulticast = false;
        proxy->suppressUnicast = false;
      }
    }
  }
}


void rtps_StatefulWriterT_resetSendOptions(struct rtps_StatefulWriter *sfw) {
  uint8_t *ptmp;
  uint8_t *pblk;
  uint8_t *pdata;
  uint32_t offset;
  ReaderProxy *proxy;//???

  RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    proxy->suppressUnicast = false;
    proxy->useMulticast = false;
    proxy->unknown_eid = false;
  }
  rtps_StatefulWriter_manageSendOptions(sfw);
}

bool statefulWriter_cmp_guid(void *pda, void *pdb)
{
  return rtps_Guid_t_operator_equal((const Guid_t *)pda, (const Guid_t *)pdb);
}
// TODO: manage Multicast Options again...

void rtps_StatefulWriterT_removeReader(struct rtps_StatefulWriter *sfw, const Guid_t *guid) {
  rtps_Lock(&sfw->m_mutex);
  rtps_MemoryPool_remove(sfw->writer.m_proxies,
			       statefulWriter_cmp_guid, (void *)guid);
  rtps_StatefulWriter_resetSendOptions(sfw);
  rtps_Unlock(&sfw->m_mutex);
}


bool statefulWriter_cmp_guidPrefix(void *pda, void *pdb)
{
  return rtps_GuidPrefix_t_operator_equal((const GuidPrefix_t *)pda, (const GuidPrefix_t *)pdb);
}

void rtps_StatefulWriterT_removeReaderOfParticipant(struct rtps_StatefulWriter *sfw,
    const GuidPrefix_t *guidPrefix) {
  rtps_Lock(&sfw->m_mutex);
  rtps_MemoryPool_remove(sfw->writer.m_proxies,
			       statefulWriter_cmp_guidPrefix, (void *)guidPrefix);
  rtps_StatefulWriter_resetSendOptions(sfw);
  rtps_Unlock(&sfw->m_mutex);
}


const CacheChange *rtps_StatefulWriterT_newChange(struct rtps_StatefulWriter *sfw,
    ChangeKind_t kind, const uint8_t *data, DataSize_t size) {
  if (rtps_StatefulWriter_isIrrelevant(kind)) {
    return NULL;
  }

  rtps_Lock(&sfw->m_mutex);

  if (rtps_SimpleHistoryCache_isFull(sfw->m_history)) {
    // Right now we drop elements anyway because we cannot detect non-responding
    // readers yet. return nullptr;
    SequenceNumber_t newMin = rtps_SimpleHistoryCache_getSeqNumMin(sfw->m_history);
    (void)rtps_SequenceNumber_t_operator_increase(&newMin);
    if (rtps_SequenceNumber_t_operator_less(&sfw->m_nextSequenceNumberToSend, &newMin)) {
      sfw->m_nextSequenceNumberToSend = newMin; // Make sure we have the correct sn to send
    }
  }

  struct rtps_CacheChange *result = rtps_SimpleHistoryCache_addChange(sfw->m_history, data, size);
  if (sfw->mp_threadPool != NULL) {
    rtps_ThreadPool_addWorkload(sfw->mp_threadPool, &sfw->writer);
  }
  SFW_LOG("Adding new data.\n");
  rtps_Unlock(&sfw->m_mutex);
  return result;
}

void rtps_StatefulWriterT_progress(struct rtps_StatefulWriter *sfw) {
  uint8_t *ptmp;
  uint8_t *pblk;
  uint8_t *pdata;
  uint32_t offset;
  ReaderProxy *proxy;//???

  if (rtps_MemoryPool_isEmpty(sfw->writer.m_proxies)) {
    SFW_LOG("Skipping progress. No proxies.\n");
    goto end;
  }
  RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    bool success;
    SFW_LOG("Progress.\n");
    proxy = (ReaderProxy *)pdata;
    if (!sfw->m_enforceUnicast) {
      success = rtps_StatefulWriter_sendDataWRMulticast(sfw, proxy, &sfw->m_nextSequenceNumberToSend);
    } else {
      success = rtps_StatefulWriter_sendData(sfw, proxy, &sfw->m_nextSequenceNumberToSend);
    }
    if (!success) {
      continue;
    }
  }
end:
  (void)rtps_SequenceNumber_t_operator_increase(&sfw->m_nextSequenceNumberToSend);
}


bool rtps_StatefulWriterT_isIrrelevant(ChangeKind_t kind) {
  // Right now we only allow alive changes
  // return kind == ChangeKind_t::INVALID || (m_topicKind == TopicKind_t::NO_KEY
  // && kind != ChangeKind_t::ALIVE);
  return kind != ALIVE;
}


void rtps_StatefulWriterT_setAllChangesToUnsent(struct rtps_StatefulWriter *sfw) {
  rtps_Lock(&sfw->m_mutex);

  sfw->m_nextSequenceNumberToSend = rtps_SimpleHistoryCache_getSeqNumMin(sfw->m_history);

  if (sfw->mp_threadPool != NULL) {
    rtps_ThreadPool_addWorkload(sfw->mp_threadPool, &sfw->writer);
  }
  rtps_Unlock(&sfw->m_mutex);
}


void rtps_StatefulWriterT_onNewAckNack(struct rtps_StatefulWriter *sfw,
    const SubmessageAckNack *msg, const GuidPrefix_t *sourceGuidPrefix) {
  ReaderProxy *reader = NULL;
  uint8_t *ptmp;
  uint8_t *pblk;
  uint8_t *pdata;
  uint32_t offset;
  ReaderProxy *proxy;//???

  RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    if (rtps_GuidPrefix_t_operator_equal(&proxy->remoteReaderGuid.prefix, sourceGuidPrefix) &&
        rtps_EntityId_t_operator_equal(&proxy->remoteReaderGuid.entityId, &msg->readerId)) {
      reader = proxy;
      break;
    }
  }

  if (reader == NULL) {
#if SFW_VERBOSE && RTPS_GLOBAL_VERBOSE
    SFW_LOG("No proxy found with id: ");
    printEntityId(msg->readerId);
    SFW_LOG(" Dropping acknack.\n");
#endif
    return;
  }

  uint8_t hash = 0;
  for (unsigned int i = 0; i < sizeof(sourceGuidPrefix->id); i++) {
    hash += sourceGuidPrefix->id[i];
  }

  char bfr[20];
  size_t size = snprintf(bfr, sizeof(bfr), "%u <= %u", msg->count.value,
                         reader->ackNackCount.value);
  if (!(size < sizeof(bfr))) {
    while (1)
      ;
  }

  if (msg->count.value <= reader->ackNackCount.value) {
    SFW_LOG("Count too small. Dropping acknack.\n");
    return;
  }

  reader->ackNackCount = msg->count;

  // Send missing packets
  SequenceNumber_t nextSN = msg->readerSNState.base;

  if (nextSN.low == 0 && nextSN.high == 0) {
    SFW_LOG("Received preemptive acknack. Ignored.\n");
  } else {
    SFW_LOG("Received non-preemptive acknack.\n");
  }

  for (uint32_t i = 0; i < msg->readerSNState.numBits; ++i, rtps_SequenceNumber_t_operator_increase(&nextSN)) {
    if (rtps_SequenceNumberSet_isSet((struct SequenceNumberSet *)&msg->readerSNState, i)) {
      SFW_LOG("Send Packet on acknack.\n");
      rtps_StatefulWriter_sendData(sfw, reader, &nextSN);
    }
  }
  // Check for sequence numbers after defined range
  SequenceNumber_t maxSN;
  {
    rtps_Lock(&sfw->m_mutex);
    maxSN = rtps_SimpleHistoryCache_getSeqNumMax(sfw->m_history);
    rtps_Unlock(&sfw->m_mutex);
  }
  while (rtps_SequenceNumber_t_operator_lessequal(&nextSN, &maxSN)) {
    rtps_StatefulWriter_sendData(sfw, reader, &nextSN);
    rtps_SequenceNumber_t_operator_increase(&nextSN);
  }
}


bool rtps_StatefulWriterT_sendData(struct rtps_StatefulWriter *sfw,
    const ReaderProxy *reader, const SequenceNumber_t *snMissing) {
  // TODO smarter packaging e.g. by creating MessageStruct and serialize after
  // adjusting values Reusing the pbuf is not possible. See
  // https://www.nongnu.org/lwip/2_0_x/raw_api.html (Zero-Copy MACs)

  rtps_PacketInfo info = {0};

  info.srcPort = sfw->m_packetInfo.srcPort;
  info.buffer = rtps_PBufWrapper_Construct(RTPS_PBW_BY_LENG, 0);
  rtps_MessageFactory_addHeader(info.buffer, &sfw->writer.m_attributes.endpointGuid.prefix);
  rtps_MessageFactory_addSubMessageTimeStamp(info.buffer, false);

  // Just usable for IPv4
  Locator *locator = (Locator *)&reader->remoteLocator;

  info.destAddr = rtps_Locator_getIp4Address(locator);
  info.destPort = (Ip4Port_t)locator->port;

  rtps_Lock(&sfw->m_mutex);
  const CacheChange *next = rtps_SimpleHistoryCache_getChangeBySN(sfw->m_history, *snMissing);
  if (next == NULL) {
    SFW_LOG("Couldn't get a CacheChange with SN (%i,%u)\n", snMissing->high,
            snMissing->low);    
    rtps_Unlock(&sfw->m_mutex);
    rtps_PBufWrapper_Destruct(info.buffer);
    return false;
  }
  rtps_MessageFactory_addSubMessageData( info.buffer, next->data, false, 
        &next->sequenceNumber, &sfw->writer.m_attributes.endpointGuid.entityId, 
        &reader->remoteReaderGuid.entityId);
  rtps_Unlock(&sfw->m_mutex);
  rtps_UdpDriver_sendPacket(sfw->m_transport, &info);
  rtps_PBufWrapper_Destruct(info.buffer);
  return true;
}


bool rtps_StatefulWriterT_sendDataWRMulticast(struct rtps_StatefulWriter *sfw,
    const ReaderProxy *reader, const SequenceNumber_t *snMissing) {

  if (reader->useMulticast || reader->suppressUnicast == false) {
    rtps_PacketInfo info = {0};

    info.srcPort = sfw->m_packetInfo.srcPort;
    info.buffer = rtps_PBufWrapper_Construct(RTPS_PBW_BY_LENG, 0);
    rtps_MessageFactory_addHeader(info.buffer, &sfw->writer.m_attributes.endpointGuid.prefix);
    rtps_MessageFactory_addSubMessageTimeStamp(info.buffer,false);

    // Deceide whether multicast or not
    if (reader->useMulticast) {
      Locator *locator = (Locator *)&reader->remoteMulticastLocator;
      info.destAddr = rtps_Locator_getIp4Address(locator);
      info.destPort = (Ip4Port_t)locator->port;
    } else {
      Locator *locator = (Locator *)&reader->remoteLocator;
      info.destAddr = rtps_Locator_getIp4Address(locator);
      info.destPort = (Ip4Port_t)locator->port;
    }

    rtps_Lock(&sfw->m_mutex);
    const CacheChange *next = rtps_SimpleHistoryCache_getChangeBySN(sfw->m_history, *snMissing);
    if (next == NULL) {
      SFW_LOG("Couldn't get a CacheChange with SN (%i,%u)\n", snMissing->high,
              snMissing->low);
      rtps_Unlock(&sfw->m_mutex);
      rtps_PBufWrapper_Destruct(info.buffer);
      return false;
    }

    EntityId_t reid;
    if (reader->useMulticast) {
      reid = ENTITYID_UNKNOWN;
    } else {
      reid = reader->remoteReaderGuid.entityId;
    }

    rtps_MessageFactory_addSubMessageData(info.buffer, next->data, false, 
              &next->sequenceNumber, &sfw->writer.m_attributes.endpointGuid.entityId, &reid);
    rtps_Unlock(&sfw->m_mutex);
    rtps_UdpDriver_sendPacket(sfw->m_transport, &info);
    rtps_PBufWrapper_Destruct(info.buffer);
  }

  return true;
}


void rtps_StatefulWriterT_hbFunctionJumppad(void *thisPointer) {
  struct rtps_StatefulWriter *writer = (struct rtps_StatefulWriter *)(thisPointer);
  rtps_StatefulWriterT_sendHeartBeatLoop(writer);
}


void rtps_StatefulWriterT_sendHeartBeatLoop(struct rtps_StatefulWriter *sfw) {
  sfw->m_thread_running = true;
  while (sfw->m_running) {
    rtps_StatefulWriter_sendHeartBeat(sfw);
#ifdef OS_IS_FREERTOS
    vTaskDelay(pdMS_TO_TICKS(SF_WRITER_HB_PERIOD_MS));
#else
    sys_msleep(SF_WRITER_HB_PERIOD_MS);
#endif
  }
  sfw->m_thread_running = false;
}


void rtps_StatefulWriterT_sendHeartBeat(struct rtps_StatefulWriter *sfw) {
  if (rtps_MemoryPool_isEmpty(sfw->writer.m_proxies)) {
    SFW_LOG("Skipping heartbeat. No proxies.\n");
    return;
  }

  uint8_t *ptmp;
  uint8_t *pblk;
  uint8_t *pdata;
  uint32_t offset;
  ReaderProxy *proxy;//???

  RTPS_MEMORYPOOL_ITER(sfw->writer.m_proxies, offset, ptmp, pblk, pdata) {
    proxy = (ReaderProxy *)pdata;
    rtps_PacketInfo info;
    SequenceNumber_t firstSN;
    SequenceNumber_t lastSN;

    info.srcPort = sfw->m_packetInfo.srcPort;
    info.destAddr = rtps_Locator_getIp4Address(&proxy->remoteLocator);
    info.destPort = proxy->remoteLocator.port;
	  info.buffer = rtps_PBufWrapper_Construct(RTPS_PBW_BY_LENG, 0);

    rtps_MessageFactory_addHeader(info.buffer, &sfw->writer.m_attributes.endpointGuid.prefix);

    rtps_Lock(&sfw->m_mutex);
    firstSN = rtps_SimpleHistoryCache_getSeqNumMin(sfw->m_history);
    lastSN = rtps_SimpleHistoryCache_getSeqNumMax(sfw->m_history);
    
    if (rtps_SequenceNumber_t_operator_equal(&firstSN, &SEQUENCENUMBER_UNKNOWN) 
      || rtps_SequenceNumber_t_operator_equal(&lastSN, &SEQUENCENUMBER_UNKNOWN)) {
      if (strlen(&sfw->writer.m_attributes.typeName[0]) != 0) {
        SFW_LOG("Skipping heartbeat. No data.\n");
      }
      rtps_Unlock(&sfw->m_mutex);
      rtps_PBufWrapper_Destruct(info.buffer);
      return;
    }
    rtps_MessageFactory_addHeartbeat(info.buffer, &sfw->writer.m_attributes.endpointGuid.entityId,
        &proxy->remoteReaderGuid.entityId, &firstSN, &lastSN, sfw->m_hbCount);
    
    rtps_Unlock(&sfw->m_mutex);
    rtps_UdpDriver_sendPacket(sfw->m_transport, &info);
    rtps_PBufWrapper_Destruct(info.buffer);
  }
  sfw->m_hbCount.value++;
}

#undef SFW_VERBOSE
